package cn.wolfcode.ssm.controller;

import cn.wolfcode.ssm.domain.Employee;
import cn.wolfcode.ssm.qo.EmployeeQueryObject;
import cn.wolfcode.ssm.qo.JsonResult;
import cn.wolfcode.ssm.service.IDepartmentService;
import cn.wolfcode.ssm.service.IEmployeeService;
import cn.wolfcode.ssm.service.IRoleService;
import com.github.pagehelper.PageInfo;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private IDepartmentService departmentService;

    @Autowired
    private IRoleService  roleService;


    @RequiresPermissions(value = {"employee:list","员工列表"},logical = Logical.OR)
    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo")EmployeeQueryObject qo) {
        PageInfo<Employee> pageInfo = employeeService.selectForPageResult(qo);
        model.addAttribute("pageInfo", pageInfo);
        //查询出所有的部门信息共享给employee/list.jsp页面
        model.addAttribute("departments",departmentService.getAll());
        return "employee/list";
    }

    @RequiresPermissions(value = {"employee:input","员工编辑"},logical = Logical.OR)
    @RequestMapping("/input")
    public String input(Model model, Long id) {
        //员工编辑时要选择部门和角色,所以要共享过去
        model.addAttribute("departments",departmentService.getAll());
        model.addAttribute("roles",roleService.getAll());
        if (id != null) {
            model.addAttribute("employee", employeeService.getOne(id));
        }
        return "employee/input";
    }

    @RequiresPermissions(value = {"employee:delete","员工删除"},logical = Logical.OR)
    @RequestMapping("/delete")
    @ResponseBody
    public JsonResult delete(Long id) {
        if (id != null) {
            employeeService.delete(id);
        }
        return new JsonResult();
    }

    //批量删除功能
    @ResponseBody
    @RequestMapping("/batchDelete")
    public JsonResult batchDelete(Long[] ids){
            employeeService.batchDelete(ids);
            return new JsonResult();
    }

    @RequiresPermissions(value = {"employee:saveOrUpdate","员工添加/更新"})
    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public JsonResult saveOrUpdate(Employee emp,Long[] ids) {//ids 角色id的数组
            if (emp.getId() != null) {
                employeeService.update(emp,ids);
            } else {
                employeeService.save(emp,ids);
            }
            return new JsonResult();
    }


    @RequestMapping("/updateStatus")
    public String updateStatus(Long id) {//ids 角色id的数组
        Employee emp = employeeService.getOne(id);
        boolean status = !emp.isStatus();
        employeeService.updateStatus(status, id);
        return "redirect:/employee/list.do";
    }



    @RequestMapping("/updatePwd")
    @ResponseBody
    public JsonResult updatePwd(String newPassword){
        //拿到当前用户的信息 在SimpleAuthenticationInfo中第一个参数传什么这里就取什么
        Employee principal = (Employee)SecurityUtils.getSubject().getPrincipal();
        //如果当前用户的密码和页面传过来的密码不一致,就执行修改密码的操作
        if(!principal.getPassword().equals(newPassword)){
            employeeService.updatePwd(newPassword,principal.getId());
            return new JsonResult(true,"密码修改成功");
        }else{
            return new JsonResult(false,"密码修改失败");
        }
    }


    //第一种方式:添加时员工可以填写用户名,编辑时用户名不能更改
   /* @RequestMapping("/checkName")
    @ResponseBody
    public Map<String,Boolean> checkName(String name){  // valid:true
        Employee employee = employeeService.selectByName(name);
        HashMap<String, Boolean> map = new HashMap<>();
        map.put("valid",employee==null);
        return map;
    }*/
   //第二种方式:添加和编辑员工用户名都可以修改
    @RequestMapping("/checkName")
    @ResponseBody
    public Map<String,Boolean> checkName(String name,Long id){  // valid:true
        HashMap<String, Boolean> map = new HashMap<>();
        System.out.println(name);
        System.out.println(id);
        if(id ==null){
            Employee employee = employeeService.selectByName(name);
            map.put("valid",employee==null);//如果员工为null,代表用户名不存在,验证通过
            return map;
        }
            Employee one = employeeService.getOne(id);
            if(one.getName().equals(name)){
                map.put("valid",true);
            }else{
                Employee employee = employeeService.selectByName(name);
                map.put("valid",employee==null);
            }
            return map;
    }
    //跳转到修改密码页面
    @RequestMapping("/goUpdate")
    public String goUpdate(){
        return "employee/updatePwd";
    }

    //跳转到密码重置页面
    @RequestMapping("/goReset")
    public String goReset(Model model,Long id){
        model.addAttribute("employee",employeeService.getOne(id));
        return "employee/resetPwd";
    }

    //执行重置密码操作
    @RequestMapping("/resetPwd")
    @ResponseBody
    public JsonResult resetPwd(String newPassword,Long id){
            employeeService.updatePwd(newPassword,id);
            return new JsonResult(true,"重置成功");
    }


    //导出excel文件
    @RequestMapping("/exportXls")
    public void exportXls(HttpServletResponse response) throws Exception {
        //设置文件下载的响应头(浏览器下载才能访问资源)
        response.setHeader("Content-Disposition","attachment;filename=employee.xls");
        //输出excel文件
        Workbook wb = employeeService.exportXls();
        //把excel的数据响应回浏览器
        wb.write(response.getOutputStream());
    }

    //导入excel文件
    @RequestMapping("/importXls")
    @ResponseBody
    public JsonResult importXls(MultipartFile file) throws Exception {
        //导入excel文件
        employeeService.importXls(file);
        return new JsonResult();
    }
}
